package org.mozhu.mboot.core.web.sitemesh;

import com.google.common.collect.Sets;
import org.mozhu.mboot.core.web.HttpServletRequestSkipper;
import org.mozhu.mboot.core.web.filter.DelegatingFilterProxy;
import org.mozhu.mboot.core.web.sitemesh.filter.DefaultConfigurableSiteMeshFilter;
import org.sitemesh.SiteMeshContext;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.StringUtils;

import java.util.Set;

@Configuration
@ConditionalOnClass({SiteMeshContext.class})
@EnableConfigurationProperties({SiteMeshProperties.class})
@AutoConfigureAfter({WebMvcAutoConfiguration.class, FreeMarkerAutoConfiguration.class,
        ThymeleafAutoConfiguration.class})
@Import(FreeMarker4SiteMeshConfiguration.class)
public class SiteMeshAutoConfiguration {

    public static String CONFIG_LOCATION_DELIMITERS = ",; \t\n";

    @Bean
    public FilterRegistrationBean siteMeshFilter(ApplicationContext applicationContext, SiteMeshProperties properties) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        HttpServletRequestSkipper httpServletRequestSkipper = new HttpServletRequestSkipper(tokenizeToStringSet(properties.getExcludeUrlPatterns()));
        registrationBean.setFilter(new DelegatingFilterProxy(new DefaultConfigurableSiteMeshFilter(applicationContext, properties), httpServletRequestSkipper));
        registrationBean.addUrlPatterns(tokenizeToStringArray(properties.getUrlPatterns()));
        return registrationBean;
    }

    private String[] tokenizeToStringArray(String source) {
        return StringUtils.tokenizeToStringArray(source, CONFIG_LOCATION_DELIMITERS);
    }

    private Set<String> tokenizeToStringSet(String source) {
        return Sets.newHashSet(tokenizeToStringArray(source));
    }
    
}
